<template>
  <Dialog width="1200px" v-model="dialogVisible" :close-on-click-modal="false" :title="(editObj?.id ? '编辑' : '新增') + '虚拟商品SKU'">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="150px"
    >
      <el-form-item label="状态：" prop="status">
        <el-radio-group
          v-model="formData.status"
          class="w-80"
        >
          <el-radio :label="EnumSkuStatus.ENABLE" class="radio">上架</el-radio>
          <el-radio :label="EnumSkuStatus.DISABLE" >下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input-number v-model="formData.sort" :min="1" />
      </el-form-item>
      <el-form-item label="SKU图片：" prop="picUrl">
        <UploadImg  v-model="formData.picUrl" height="80px" />
        （推荐 480*254 图片分辨率）
      </el-form-item>
      <el-form-item label="SKU名称：" prop="name">
        <el-input  v-model="formData.name" placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="SKU描述：" prop="introduction">
        <el-input  v-model="formData.introduction" placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="最低起购件数：" prop="minPurchaseQuantity">
        <el-input-number  v-model="formData.minPurchaseQuantity" :min="1" />
      </el-form-item>
      <el-form-item label="最高起购件数：" prop="maxPurchaseQuantity">
        <el-input-number v-model="formData.maxPurchaseQuantity" :min="1" />
      </el-form-item>
      <el-form-item label="是否自定义面值：" prop="customDenomination">
        <el-radio-group
          v-model="formData.customDenomination"
          @change="changeCustomDenomination"
          class="w-80"
        >
          <el-radio :label="false">否</el-radio>
          <el-radio :label="true" class="radio">是</el-radio>
        </el-radio-group>
        <div >
          最小面值：<el-input-number :disabled="!formData.customDenomination" v-model="formData.minCustomDenomination" :min="0" />
          最大面值：<el-input-number :disabled="!formData.customDenomination" v-model="formData.maxCustomDenomination" :min="0" />
        </div>
      </el-form-item>
      <el-form-item :label="'面值描述：'" prop="denomination">
        <el-input v-model="formData.denomination" placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="固定面值折扣率(%)" prop="discountRate">
        <el-input-number @change="changeDiscountRate" v-model="formData.discountRate" :min="0.01" :step="0.01" />
        (折扣输入小于100,溢价输入大于100。)
      </el-form-item>
      <el-form-item v-if="!formData.customDenomination" :label="'固定面值：' + (currencyData ? '(' + currencyData.currencyName + ')' : '')" prop="denominationFixed">
        <el-input-number v-model="formData.denominationFixed" :min="0.01" :precision="2" :step="0.01" />
      </el-form-item>
      <el-form-item :label="'售价：' + (currencyData ? '(' + currencyData.currencyName + ')' : '')" prop="price">
        <el-input-number @change="changePrice" v-model="formData.price" :min="0" />
      </el-form-item>
      <el-form-item label="发货方式：" prop="deliveryMethod">
        <el-radio-group
          v-model="formData.deliveryMethod"
          class="w-80"
        >
          <el-radio :label="EnumDeliveryMethodType.AUTOMATIC">自动</el-radio>
          <el-radio :label="EnumDeliveryMethodType.MANUAL" class="radio">手动</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.deliveryMethod === EnumDeliveryMethodType.AUTOMATIC" label="关联CDK：" prop="cardKeyProductNo">
        <el-button @click="showCDKChooser" size="small">选择关联</el-button>
      </el-form-item>
    </el-form>
    <VirtualProductSkuChoosedCardKeyInfo :data="cardKeyProduct" v-if="!cardKeyProductLoading && formData.deliveryMethod === EnumDeliveryMethodType.AUTOMATIC && formData.cardKeyProductNo" style="width:1000px;margin-left:40px;" />
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <CDKChooser @choose="chooseCDKHandler" ref="cdkChooserRef" />
</template>
<script lang="ts" setup>
import {propTypes} from "@/utils/propTypes";
import {createSku, updateSku} from '@/api/mall/product/spu';
import {getCardkeyByNo} from '@/api/digital/cardkeyproduct/index';
import VirtualProductSkuChoosedCardKeyInfo from './VirtualProductSkuChoosedCardKeyInfo.vue';
import CDKChooser from '@/views/digital/cardkeyproduct/components/Chooser.vue';
import {EnumDeliveryMethodType, EnumSkuStatus} from "@/config/spu";
import * as ProductSpuApi from "@/api/mall/product/spu";
import {ExchangeRateApi} from "@/api/mall/currency/rate/index";
import {useUpload} from "@/components/UploadFile/src/useUpload";
import {downloadImgByUrl} from "@/utils/file";
import {uploadByUrl} from "@/api/infra/file";

import {Decimal} from 'decimal.js';
defineOptions({ name: 'ProductVirtualProductSkuUpdateForm' })
const { uploadUrl, httpRequest } = useUpload()
const props = defineProps({
  spuId: propTypes.number.def(undefined),
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
})
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const editObj = ref(null);
const cdkChooserRef = ref();
let cardKeyProduct = ref(null);
const cardKeyProductLoading = ref(false);
const spuData = ref({});
const currencyData = ref({})
const formData = ref({
  spuId: undefined,
  id: undefined,
  status: EnumSkuStatus.DISABLE,
  sort: 0,
  name: '',
  picUrl: '',
  introduction: '',
  discountRate: undefined,
  minPurchaseQuantity: 0,
  maxPurchaseQuantity: 0,
  minCustomDenomination: 0,
  maxCustomDenomination: 0,
  denominationFixed: 0,
  customDenomination: false,
  denomination: "",
  price: 0,
  // stock: 0,
  deliveryMethod: EnumDeliveryMethodType.AUTOMATIC,
  cardKeyProductNo: undefined,
})
const formRules = reactive({
  status: [{ required: true, message: '', trigger: 'blur' }],
  sort: [{ required: true, message: '', trigger: 'blur' }],
  name: [{ required: true, message: '', trigger: 'blur' }],
  picUrl: [{ required: true, message: '', trigger: 'blur' }],
  discountRate: [{ required: true, message: '', trigger: 'blur' }],
  minPurchaseQuantity: [{ required: true, message: '', trigger: 'blur' }],
  maxPurchaseQuantity: [{ required: true, message: '', trigger: 'blur' }],
  minCustomDenomination: [{ required: true, message: '', trigger: 'blur' }],
  maxCustomDenomination: [{ required: true, message: '', trigger: 'blur' }],
  customDenomination: [{ required: true, message: '', trigger: 'blur' }],
  denomination: [{ required: true, message: '', trigger: 'blur' }],
  price: [{ required: true, message: '', trigger: 'blur' }],
  deliveryMethod: [{ required: true, message: '', trigger: 'blur' }],
  cardKeyProductNo: [{ required: true, message: '请设置关联CDK', trigger: 'blur' }],
  denominationFixed: [{ required: true, message: '', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const emit = defineEmits(['updateSuccess', "createSuccess"])

watch(
  () => formData.value.deliveryMethod,
  (newValue) => {
    if(!spuData.value.id) {
      return;
    }

    if(newValue === EnumDeliveryMethodType.AUTOMATIC) {
      formRules.cardKeyProductNo[0].required = true;
    } else {
      formData.value.cardKeyProductNo = undefined;
      formRules.cardKeyProductNo[0].required = false;
      cardKeyProduct.value = null;
    }
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => formData.value.customDenomination,
  (newValue) => {
    if(!spuData.value.id) {
      return;
    }

    if(newValue) {
      formRules.denominationFixed[0].required = false;
      formData.value.denominationFixed = undefined;
    } else {
      formRules.denominationFixed[0].required = true;
    }
  },
  {
    deep: true,
    immediate: true
  }
)

watch(()=>formData.value.denominationFixed, ()=> {
  if(!spuData.value.id) {
    return;
  }
  if(formData.value.discountRate && formData.value.denominationFixed) {
    formData.value.price = formData.value.denominationFixed * (formData.value.discountRate / 100);
  }
});

const changeDiscountRate = ()=> {
  if(!spuData.value.id) {
    return;
  }

  if(formData.value.customDenomination) {
    // 非自定义面额，售价的面额是1，
    formData.value.price = 1 * (formData.value.discountRate / 100);
  } else {
    if(formData.value.denominationFixed) {
      formData.value.price = formData.value.denominationFixed * (formData.value.discountRate / 100);
    }
  }
}

const changePrice = ()=> {
   if(!formData.value.customDenomination) {
     if(formData.value.denominationFixed) {
       formData.value.discountRate = (formData.value.price / formData.value.denominationFixed * 100).toFixed(2);
     }
   } else {
     formData.value.discountRate = (formData.value.price / 1 * 100).toFixed(2);
   }
 }

const changeCustomDenomination = ()=> {
  if(formData.value.customDenomination) {
    formData.value.price = 1;
  }
}

const getCardKeyData = async ()=> {
  if(!formData.value.cardKeyProductNo || formData.value.deliveryMethod !== EnumDeliveryMethodType.AUTOMATIC) {
    return;
  }

  return new Promise(resolve => {
    cardKeyProductLoading.value = true;
    getCardkeyByNo({
      productNo: formData.value.cardKeyProductNo
    }).then((data)=> {
      cardKeyProduct.value = data;
      if(!formData.value.customDenomination && data.denominationFixed) {
        formData.value.denominationFixed = data.denominationFixed / 100;
        // if(spuData.value && spuData.value.discountRate && formData.value.price != formData.value.denominationFixed) {
        //   formData.value.price = formData.value.denominationFixed * (spuData.value.discountRate / 100);
        // } else {
        //   formData.value.price = formData.value.denominationFixed;
        // }
      }
    }).finally(()=> {
      cardKeyProductLoading.value = false;
      resolve(true);
    });
  })
}

const getCurrencyRateData = ()=> {
  if(!spuData.value.currencyCode) {
    return;
  }

  ExchangeRateApi.getExchangeRatePage({
    pageNo: 1,
    pageSize: 1,
    currencyCode: spuData.value.currencyCode
  }).then(({list})=> {
    if(list.length) {
      currencyData.value = list[0];
    }
  });
}

const getSpuDetail = async ()=> {
  if(props.spuId) {
    const res = (await ProductSpuApi.getSpu(props.spuId)) as ProductSpuApi.Spu

    spuData.value = res;
    if(typeof formData.value.discountRate === "undefined") {
      formData.value.discountRate = spuData.value.discountRate;
      changeDiscountRate();
    }
    getCurrencyRateData();
  }
}

/** 打开弹窗 */
const open = async (obj?: any) => {
  dialogVisible.value = true
  editObj.value = obj;
  spuData.value = {};

  let newFormData = {
    spuId: undefined,
    id: undefined,
    status: EnumSkuStatus.DISABLE,
    sort: 0,
    name: '',
    picUrl: '',
    introduction: '',
    minPurchaseQuantity: 0,
    discountRate: undefined,
    maxPurchaseQuantity: 0,
    minCustomDenomination: 0,
    maxCustomDenomination: 0,
    denominationFixed: 0,
    customDenomination: false,
    denomination: "",
    price: 0,
    deliveryMethod: EnumDeliveryMethodType.AUTOMATIC,
    cardKeyProductNo: undefined,
  };

  // 获取数据
  if (obj) {
    Object.assign(newFormData, obj);
    if(newFormData.price) {
      newFormData.price = new Decimal(newFormData.price).div(100).toNumber();
    }
    if(newFormData.denominationFixed) {
      newFormData.denominationFixed = new Decimal(newFormData.denominationFixed).div(100).toNumber();
    }
    if(newFormData.minCustomDenomination) {
      newFormData.minCustomDenomination = new Decimal(newFormData.minCustomDenomination).div(100).toNumber();
    }
    if(newFormData.maxCustomDenomination) {
      newFormData.maxCustomDenomination = new Decimal(newFormData.maxCustomDenomination).div(100).toNumber();
    }

    formData.value = newFormData;
    await getCardKeyData();
  } else {
    formData.value = newFormData;
  }
  getSpuDetail();
}

const close = async ()=> {
  dialogVisible.value = false;
}

const chooseCDKHandler = async (item)=> {
  // 如果选择cdk的货币跟spu货币不一致，给出提示
  if(item.currencyCode !== spuData.value.currencyCode) {
    try {
      await message.confirm("关联CDK与商品货币类型不一致，请确认是否要关联？", undefined, "取消设置")
      formData.value.cardKeyProductNo = item.productNo;
      cdkChooserRef.value.close();
    } catch(e) {
      cdkChooserRef.value.close();
    }
  } else {
    formData.value.cardKeyProductNo = item.productNo;
    cdkChooserRef.value.close();
  }
  if(formData.value.cardKeyProductNo) {
    await getCardKeyData();

    // 如果当前sku没有图片，从cdk里面找出来下载上传，目前下载图片跨域，先暂停该行为
    if(!formData.value.picUrl && cardKeyProduct.value && cardKeyProduct.value.imageUrls) {
      let imageUrls = JSON.parse(cardKeyProduct.value.imageUrls);
      let distImage = imageUrls.find(item=> {
        return item.iamgeSize === "EXTRA_EXTRA_LARGE";
      });
      if(!distImage) {
        distImage = imageUrls[imageUrls.length - 1]
      }
      let res = await uploadByUrl({
        imageUrl: distImage.frontImage
      });
      if(res) {
        message.success("商品图片上传成功");
        formData.value.picUrl = res;
      }
    }
  }
}

const showCDKChooser = ()=> {
  cdkChooserRef.value.open();
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return

  console.log(formData.value);
  let data = {
    ...formData.value
  };
  try {
    data.spuId = +props.spuId as number;
    let price = new Decimal(formData.value.price).mul(100).toNumber();
    data.price = price;
    if(price < 1) {
      message.warning("售价不得小于1分")
      return;
    }

    formLoading.value = true;
    // 如果是自定义，去掉固定值
    if(data.customDenomination) {
      delete data.denominationFixed;
      data.minCustomDenomination = new Decimal(formData.value.minCustomDenomination).mul(100).toNumber();
      data.maxCustomDenomination = new Decimal(formData.value.maxCustomDenomination).mul(100).toNumber();
    } else { // 去掉自定义值
      delete data.minCustomDenomination;
      delete data.maxCustomDenomination;
      data.denominationFixed = new Decimal(formData.value.denominationFixed).mul(100).toNumber();
    }

    // // 修复历史数据
    // if(!data.stock) {
    //   data.stock = 2147483647;
    // }
    if(data.id) {
      await updateSku(data)
      emit("updateSuccess");
      message.success("更新成功")
    } else {
      await createSku(data);
      emit("createSuccess");
      message.success("创建成功")
    }
    formLoading.value = false
  } catch (e) {
    formLoading.value = false
  }
}
</script>
